<template>
  <div class="add">
    <el-breadcrumb separator="/" style="padding-left: 15px;padding-top: 15px;">
      <el-breadcrumb-item :to="{ path: '/main/test/integrate' }">集成测试列表</el-breadcrumb-item>
      <el-breadcrumb-item>{{title}}</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="body">
      <el-steps :active="activeIndex" align-center>
        <el-step title="填写信息" ></el-step>
        <el-step title="选择接口" ></el-step>
        <el-step title="选择用例" ></el-step>
      </el-steps>

      <!--第一步-->
      <transition name="show">
        <div class="body-item edit" v-show="activeIndex === 1">
          <el-form :model="dataForm" label-width="140px" size="mini" :disabled="addDisabled">
            <el-form-item label="集成测试名称" prop="name" :rules="{ required: true, message: '请输入集成测试名称' }">
              <el-input v-model="dataForm.name" placeholder="请输入集成测试名称" maxlength="20"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark" :rules="{ max:200,message: '最多200个字节' }">
              <el-input type="textarea" v-model="dataForm.remark" placeholder="请输入备注" :rows="5"></el-input>
            </el-form-item>
            <el-form-item >
              <task-plan-set ref="plan" :execute-plan-data="executePlanData" :disabled="addDisabled"/>
            </el-form-item>
          </el-form>
        </div>
      </transition>

      <!--第二步-->
      <transition name="show">
        <div class="body-item service-list-item" v-show="activeIndex === 2">
          <div class="flex">
            <div class="flex-left">
              <div class="title">接口名称</div>
              <div class="border" style="padding: 0;">
                <el-row class="height">
                  <el-col :span="6" class="height">
                    <service-list @serviceCall="serviceCall"/>
                  </el-col>
                  <el-col :span="18" class="height">
                    <test-tools v-if="isTestTools" @doDataShow="doDataShow" :zySid="sId" :zyDataList="icons"/>
                  </el-col>
                </el-row>
              </div>
            </div>
            <div class="flex-right">
              <div class="title">测试接口</div>
              <div class="border">
                <interface-list :interface-data="interfaceData"/>
              </div>
            </div>
          </div>
        </div>
      </transition>

      <!--第三步-->
      <transition name="show">
        <div class="body-item border-item" v-show="activeIndex === 3">
          <el-row class="height">
            <el-col :span="10" class="height">
              <el-row class="height">
                <el-col :span="12" class="height">
                  <div class="interface-bar">
                    <div class="interface-div">
                      <div class="title">接口名称</div>
                      <interface-list :interface-data="interfaceData" @clickRowCall="clickInterfaceCall" @deleteCall="deleteCall"/>
                    </div>
                  </div>
                </el-col>
                <el-col :span="12" class="height">
                  <div class="use-case-bar">
                    <div class="title">测试用例
                      <el-button type="danger" size="mini" class="fr" @click="deleteUseCase">批量删除</el-button>
                      <el-button type="primary" size="mini" class="fr" @click="onClickQuote" style="margin-right: 10px">引用</el-button>
                    </div>
                    <test-use-case-list :use-list="useCaseList" @selectionChange="selectionChange" @rowClickTestUse="rowClickTestUse" @rowClickDelete="rowClickDelete"/>
                  </div>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="14" class="height">
              <div class="interface-config-bar">
                <div class="interface-config">
                  <interface-config ref="interfaceConfig" v-if="isInterfaceConfig" disabled :node="node" />
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </transition>

    </div>


    <div class="btn-bar">
      <el-button v-if="activeIndex > 1" type="primary" size="mini" @click="activeIndex === 2 ? activeIndex = 1 : activeIndex = 2">上一步</el-button>
      <el-button v-if="activeIndex < 3" type="primary" size="mini" @click="next">下一步</el-button>
      <el-button v-if="activeIndex === 3" type="primary" size="mini" @click="save">保存</el-button>
    </div>

    <el-dialog title="接口详情" :visible.sync="isDetails" append-to-body width="90%">
      <interface-details :node="node" v-if="isDetails"/>
    </el-dialog>

    <CaseList v-if="isUseCase" ref="caseList"
              @useListCall="useListCall"
              @closeCaseCall="closeCaseCall"
              :history-list="useCaseList"
              :type="2"
              :dialogVisibleCase="isUseCase"
              :node="node"/>

  </div>
</template>

<script>

  import TaskPlanSet from "./TaskPlanSet"
  import TestTools from '@/rdComponent/common/testTools'
  import ServiceList from '@/rdComponent/common/ServiceList'
  import InterfaceDetails from "@/rdComponent/common/InterfaceDetails";
  import SelectUseCase from './SelectUseCase'
  import InterfaceList from './InterfaceList';
  import TestUseCaseList from './TestUseCaseList';
  import CaseList from '../../useCase/component/CaseList'
  import InterfaceConfig from "@/rdComponent/common/InterfaceConfig";
  export default {
    components: {
      InterfaceConfig,
      InterfaceDetails, InterfaceList, TestUseCaseList,
      TaskPlanSet, TestTools, ServiceList, SelectUseCase, CaseList
    },
    name: "Add",
    data() {
      return {
        type: 0,
        addDisabled: true,
        detail: {},
        detailDialog: false,
        activeIndex: 1,
        dataForm: {
          name: "",
          remark: "",
        },

        isTestTools: true,
        sId: "",
        icons: [
          {
            name: "添加",
            isIcon: true,
            iconName: "el-icon-plus",
            btnIndex: 1,
          },
          {
            name: "查看",
            isIcon: true,
            iconName: "el-icon-document",
            btnIndex: 2,
          }
        ],
        interfaceData: [],
        node: {},
        isDetails: false,
        isUseCase: false,
        isInterfaceConfig: false,
        useCaseList: [],
        tmpUseCaseList: [],/*编辑功能*/
        tmpArrInf: [],
        executePlanData: {},
        multipleSelection: [],
        title: "添加集成与性能测试",
      }
    },
    created() {
      console.log(this.$route.params);
      if (Object.keys(this.$route.params).length === 0) {
        this.addDisabled = false;
        return;
      }
      this.type = this.$route.params.type;
      this.addDisabled = this.$route.params.disabled;
      this.detail = this.$route.params.detail;
      let that = this;
      if (Object.keys(this.detail).length > 0) {
        console.log("detail: ", this.detail);
        this.dataForm = this.detail;
        this.executePlanData = JSON.parse(this.detail.executePlanData) || {};
      }
      switch (this.type) {
        case 0: this.title = "新增集成与性能测试"; break;
        case 1:
          this.title = "修改集成与性能测试";
          this.tmpUseCaseList = [];
          this.tmpArrInf = [];
          this.interfaceData = [];
          this.detail.interfaces.forEach(function (item) {
            that.tmpArrInf.push(item.interfaceId);
            $.ajax({
              url:'/api/center/interface?siaId=' + item.interfaceId,
              type:'GET',
              async:false,
              success:function(data,textStatus,jqXHR){
                that.interfaceData.push(data)
              },
            })
            let tmpArr = [];
            item.assos.forEach(function (caseItem) {
              tmpArr.push({
                "useCaseName": caseItem.testUseCase.remark,
                "id": caseItem.tucId,
              });
            })
            that.tmpUseCaseList.push(tmpArr);
          })
          break;
        default: this.title = "查看集成与性能测试"; break;
      }
    },
    methods: {
      /**下一步**/
      next() {
        switch (this.activeIndex) {
          case 1:
            this.checkForm();
            break;
          case 2:
            if(this.interfaceData.length === 0) {
              this.$message.warning("至少要选择一个接口");
              return;
            }
            this.activeIndex = 3;
            if(this.type == 1)
              this.clickInterfaceCall(this.interfaceData[0])
            break;
        }
      },
      /**表单输入验证**/
      checkForm (){
        let reg = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im;
        let numReg = /^[1-9]\d*$/;
        if (this.dataForm.name.trim() === "") {
          this.$message.error("测试任务名称");
          return;
        }
        if (reg.test(this.dataForm.name)) {
          this.$message.error("测试任务名称不能包含特殊符号");
          return;
        }
        let planForm = this.$refs.plan.getExecutePlanData();
        if(this.$refs.plan.executeChecked) {
          if (!planForm.loopTime || planForm.loopTime.length === 0) {
            this.$message.warning("请选择测试时间");
            return;
          }
          for (let i = 0;i < planForm.executeList.length; i++) {
            if (!planForm.executeList[i].concurrentCount || !planForm.executeList[i].startTime || !planForm.executeList[i].endTime) {
              this.$message.warning("请完善通用计划信息");
              return;
            }
            if (planForm.executeList[i].concurrentCount < 1) {
              this.$message.warning("并发数不能小于1");
              return;
            }
            if (!numReg.test(planForm.executeList[i].concurrentCount)) {
              this.$message.warning("并发数必须是正整数");
              return;
            }
          }
          if (this.$refs.plan.specialChecked){
            for (let i = 0;i < planForm.specialList.length; i++){
              if (!planForm.specialList[i].specialTime || !planForm.specialList[i].startTime || !planForm.specialList[i].endTime || !planForm.specialList[i].concurrentCount){
                this.$message.warning("请完善特殊计划信息");
                return;
              }
              if (planForm.specialList[i].concurrentCount < 1) {
                this.$message.warning("并发数不能小于1");
                return;
              }
              if (!numReg.test(planForm.specialList[i].concurrentCount)) {
                this.$message.warning("并发数必须是正整数");
                return;
              }
            }
          }
          this.dataForm.startTime = new Date(planForm.loopTime[0]);
          this.dataForm.endTime = new Date(planForm.loopTime[1]);
          this.dataForm.executePlanData = JSON.stringify(planForm);
          this.dataForm.integrationTestTriggerParams = this.$refs.plan.createdData();
        }
        this.activeIndex = 2;
      },
      /**选择服务列表回调**/
      serviceCall(sId) {
        this.sId = sId;
        this.isTestTools =  false;
        this.$nextTick(()=>{
          this.isTestTools = true;
        })
      },
      /**选择要测试的接口**/
      doDataShow(row){
        switch (row.fn) {
          case 1:
            let bool = false;
            for (let i = 0; i < this.interfaceData.length; i++) {
              if (this.interfaceData[i].siaId === row.data.siaId) {
                bool = true;
                break;
              }
            }
            if (bool) {
              this.$message.warning("已添加该接口了.");
              return;
            }
            this.interfaceData.push(row.data);
            break;
          case 2:
            this.isDetails = false;
            this.$nextTick(() => {
              this.isDetails = true;
              this.node = row.data;
            });
            break;
        }
      },
      /**点击接口行回调**/
      clickInterfaceCall(row) {
        let idx = 0;
        this.node = JSON.parse(JSON.stringify(row));
        for(let i=0; i<this.tmpArrInf.length; i++){
          if(row.siaId == this.tmpArrInf[i]){
            idx = i;
            break;
          }
        }
        if(row.useData == undefined && this.type == 1){/*代表编辑状态*/
          this.useCaseList = this.tmpUseCaseList[idx]
          this.interfaceData[idx].useData = this.tmpUseCaseList[idx];
        }
        else
          this.interfaceData.forEach(item => {
            if(item.siaId === row.siaId){
              this.useCaseList = row.useData;
            }
          })
        this.isInterfaceConfig = false;
        this.$nextTick(() => {
          this.isInterfaceConfig = true;
        });
      },
      /**删除接口回调**/
      deleteCall(len, id) {
        if (len === 0) {
          this.activeIndex = 2;
          this.isInterfaceConfig = false;
        }
        else {
          /*if (this.node.siaId === id) {
            this.node = {};
            this.isInterfaceConfig = false;
          }*/
        }
      },
      /**批量删除用例**/
      deleteUseCase() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning("请选择测试用例.");
          return;
        }
        this.$confirm('您确定删除该用例吗?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.multipleSelection.forEach(item => {
            for (let i = 0; i < this.useCaseList.length; i++) {
              if (this.useCaseList[i].id === item.id) {
                this.useCaseList.splice(i, 1);
              }
            }
          })
        })
      },
      /**点击引用按钮**/
      onClickQuote(){
        //if (!this.node) {
        if(Object.keys(this.node).length == 0){
          this.$message.warning("请选择接口.");
          return;
        }
        this.isUseCase = false;
        this.$nextTick(()=>{
          this.isUseCase = true;
        })
      },
      /**勾选用例集合回调**/
      selectionChange(val) {
        this.multipleSelection = val;
      },
      /**点击用例列表行**/
      rowClickTestUse(row) {
        this.axios.get(this.interfaceUrl.path + '/test/use/case/' + row.id)
          .then((res) => {
            this.node.updateInterfaceJson = JSON.parse(res.data.data.inBody);
            this.node.updateParamsJson = {
              inHeader: JSON.parse(res.data.data.inHeader),
              inQuery: JSON.parse(res.data.data.inQuery)
            };
            this.node.updateAssertJson = res.data.data.assertConditions;
            this.isInterfaceConfig = false;
            this.$nextTick(() => {
              this.isInterfaceConfig = true;
              this.addDisabled = true;
            })
            this.form = {
              useCaseName: res.data.data.useCaseName,
              remark: res.data.data.remark
            }
          })
      },
      /**点击删除用例列表按钮**/
      rowClickDelete(row) {
        this.$confirm('您确定删除该用例吗?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.useCaseList.forEach((item,index)=>{
            if (row.id === item.id) {
              this.useCaseList.splice(index, 1)
            }
          })
        })
      },
      /**引用回调**/
      useListCall(data){
        this.useCaseList = data.useList;
        this.interfaceData.forEach((item,index)=>{
          if(item.siaId == data.id) {
            this.interfaceData[index].useData = data.useList;
          }
        });
        this.isUseCase = false;
      },
      /**点击引用关闭弹出按钮**/
      closeCaseCall() {
        this.isUseCase = false;
      },
      /**获取选择接口用例数据结构**/
      getInterfaces(){
        let interfaces = [];
        this.interfaceData.forEach((item)=> {
          let interfacesItem = {
            assos: []
          };
          if (item.useData) {
            item.useData.forEach(i => {
              interfacesItem.assos.push({
                tucId: i.id
              })
            });
          }
          interfacesItem.interfaceId = item.siaId;
          interfacesItem.interfaceName = item.siaName;
          interfaces.push(interfacesItem);
        });
        return interfaces;
      },
      /**保存**/
      save() {
        this.dataForm.interfaces = this.getInterfaces();
        for (let i = 0; i < this.dataForm.interfaces.length; i++) {
          if (this.dataForm.interfaces[i].assos.length === 0) {
            this.$message.error("每个接口下面至少添加一个用例.");
            return;
          }
        }
        console.log(this.dataForm);
        if(this.type == 0)
          this.axios.post("/api/integration/test", this.dataForm).then(res => {
            if (res.data.status === 0) {
              if (this.dataForm.id) {
                this.$message.success("修改成功.");
              }
              else {
                this.$message.success("添加成功.");
              }
              this.$router.push({
                name: "list"
              })
            }
            else {
              this.$message.error(res.data.msg);
            }
          })
        else
          this.axios.put("/api/integration/test", this.dataForm).then(res => {
            if (res.data.status === 0) {
              if (this.dataForm.id) {
                this.$message.success("修改成功.");
              }
              else {
                this.$message.success("添加成功.");
              }
              this.$router.push({
                name: "list"
              })
            }
            else {
              this.$message.error(res.data.msg);
            }
          })
      }
    }
  }
</script>

<style>
  .el-step.is-simple .el-step__icon{top: 5px;}
  .el-dialog__body{background: #fff}
</style>
<style scoped lang="less">
  .add{
    border: 20px solid #e2eaed;
  }
  .body{
    height: 720px;
    padding: 15px;
    &-item{
      height: calc(100% - 60px);
    }
    .edit{
      border-radius: 6px;
      background: #f5f5f5;
      padding: 30px 50px 15px 15px;
      width: 60%;
      margin: 15px auto;
      overflow-y: auto
    }
    .title{
      font-size: 18px;
      color:#409eff;
      padding-bottom: 10px;
      font-weight: bold;
    }
    .border{
      border: 1px solid #e1e1e1;
      padding: 15px;
      height: 100%;
    }
    .border-item{
      border: 1px solid #e1e1e1;
      padding: 0 15px;
      margin-top: 15px;
    }
    .service-list-item{
      padding: 15px;
      .flex{
        display: flex;
        height: 100%;
        .flex-left{
          height: 100%;
          width: calc(100% - 300px);
        }
        .flex-right{
          height: 100%;
          width: 300px;
          padding-left: 15px;
          box-sizing: border-box;
        }
      }
    }
    .interface-bar{
      background: rgba(245, 245, 245, 1);
      padding-right: 15px;
      height: 100%;
      .interface-div{
        height: 100%;
        padding-top: 15px;
        background: #fff;
        padding-right: 15px;
      }
    }
    .use-case-bar{
      padding: 15px 15px 0 15px;
    }
    .interface-config-bar{
      height: 100%;
      background: rgba(245, 245, 245, 1);
      padding-left: 15px;
      box-sizing: border-box;
      .interface-config{
        height: 100%;
        padding: 15px;
        background: #fff;
        overflow-y: auto;
      }
    }
  }
  .api_info{padding: 5px 15px;
    span{color:#999;padding-left:10px;}
  }
  .btn-bar{
    text-align: center;
    padding: 15px;
  }
  .height{
    height: 100%;
  }

</style>
